<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-row :gutter="10" type="flex" justify="space-around" align="middle">
      <a-col :span="7">
        <a-card title="可选角色列表" :bodyStyle="bodyStyle" style="overflow: auto;max-height: 58vh;" ref="roleCard">
          <a-input-search @search="onSearch" style="width:100%;margin-top: 10px" placeholder=""/>
          <a-tree
            checkable
            multiple
            :checkedKeys="checkedKeys"
            :selectedKeys="selectedKeys"
            :treeData="tenantRoleTree"
            :replaceFields="tenantRoleFileds"
            :autoExpandParent="autoExpandParent"
            @check="onCheck"
          />
        </a-card>
      </a-col>
     <a-col :span="1">
        <a-button type="primary" @click="selectTenantRole" size="small">
          <a-icon type="right" />
        </a-button>
        <a-button type="default" @click="cancelTenantRole" size="small" style="margin-top:3px">
          <a-icon type="left" />
        </a-button>
      </a-col>
      <a-col :span="7">
        <a-card title="已选应用列表" :bodyStyle="bodyStyle" style="overflow: auto;max-height: 58vh;" ref="appCard">
          <a-tree
            checkable
            :selectedKeys="selectedKeysRole"
            :checkedKeys="checkedKeysRoleApp"
            :treeData="selectedRoleApp"
            :autoExpandParent="autoExpandParentRole"
            :replaceFields="selectedRoleAppFileds"
            @check="onCheckRoleApp"
            @select="onSelectApp"
          />
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card title="权限" :bodyStyle="bodyStyle" style="overflow: auto;max-height: 58vh;" ref="permissionCard">
          <a-tree
            checkable
            multiple
            :checkedKeys="checkedPermission"
            :treeData="permissionData"
            :autoExpandParent="autoExpandParentPermission"
            :selectedKeys="selectedKeys"
            @check="onCheckPermission"
            @select="onTreeNodeSelect">
            <span slot="hasDatarule" slot-scope="{slotTitle,ruleFlag}">
              {{ slotTitle }}<a-icon v-if="ruleFlag" type="align-left" style="margin-left:5px;color: red;"></a-icon>
            </span>
          </a-tree>
        </a-card>
      </a-col>
    </a-row>

  </j-modal>
</template>

<script>

import { queryRoleLeafPermission, queryRolePermission, queryTenantRoleAppTree, saveTenantRoleAppPermission, simpleTenantRoleAppTree, simpleTenantRoleTree } from '../service';

  export default {
    name: 'TenantRoleModal',
    components: {
    },
    data () {
      return {
        title: '组织角色授权',
        width: 900,
        visible: false,
        roleId: '',
        tenantId: '',
        // 可选角色列表
        checkedKeys: [],
        tenantRoleTree: [],
        autoExpandParent: true,
        tenantRoleFileds: {
          title: 'roleName',
          key: 'roleId'
        },

        // 已选角色
        selectedKeysRole: [],
        checkedKeysRoleApp: [],
        selectedRoleApp: [],
        autoExpandParentRole: true,
        selectedRoleAppFileds: {
          title: 'appName',
          key: 'key'
        },

        // 已选角色权限
        checkedPermission: [],
        permissionData: [],
        autoExpandParentPermission: true,

        savePermissions: {},
        currentRoleId: '',
        currentAppId: '',
        selectedKeys: [],

        bodyStyle: { 'min-height': '500px' },
        appPermissionMap: new Map(),
        selectedApp: {}
      }
     },
    methods: {
       onTreeNodeSelect(id) {
        if (id && id.length > 0) {
          this.selectedKeys = id
        }
        this.$refs.datarule.show(this.selectedKeys[0], this.roleId)
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      edit (record) {
        this.checkedKeysRoleApp = [];
        this.visible = true
        this.roleId = record.id
        this.tenantId = record.tenantId;
        this.permissionData = [];
        this.selectedKeysRole = [];
        this.selectedKeys = []
        this.appPermissionMap = new Map()
        this.checkedPermission = [];
        this.loadTenantRoleTree();
        this.loadSelectedRoleAppTree(record.tenantId, record.id);
        this.$nextTick(() => {
          this.$refs.roleCard.$el.scrollTop = 0
          this.$refs.appCard.$el.scrollTop = 0
          this.$refs.permissionCard.$el.scrollTop = 0
        })
      },
      handleSubmit(exit) {
        let that = this;
        let params = {
          roleId: that.roleId,
          appPermission: []
        }
        if (that.selectedRoleApp && that.selectedRoleApp.length === 0) {
          that.$message.warn('已选应用列表为空');
          return false
        }

        let selectedRoles = that.selectedRoleApp;
        let isSuccess = true
        selectedRoles.forEach(function(roleApp) {
           let key = that.getKey(roleApp.roleId, roleApp.appId);
           let appPermission = that.appPermissionMap.get(key)
           if (!appPermission || appPermission.permissionIds.length === 0) {
             that.$message.warning('请选择【' + roleApp.appName + '】的菜单/按钮权限');
             isSuccess = false;
             return false
           }
           params.appPermission.push({ 'appId': roleApp.appId, 'permissionIds': appPermission.permissionIds });
        });
        if (isSuccess) {
          that.loading = true;
          saveTenantRoleAppPermission(params).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.loading = false;
              that.$emit('ok');
              if (exit) {
                that.close()
              }
            } else {
              that.$message.error(res.message);
              that.loading = false;
              if (exit) {
                that.close()
              }
            }
          })
        }
      },
      handleCancel () {
        this.close()
      },

      loadTenantRoleTree(appName) {
        let that = this;
        let param = {
          name: appName || ''
        }
        simpleTenantRoleTree(that.tenantId, param).then(res => {
          if (res.success) {
            that.tenantRoleTree = res.result;
            that.checkedKeys = [];
          } else {
            this.$message.error(res.message)
          }
        }).finally(() => {})
      },
      onSearch(value) {
        this.loadTenantRoleTree(value)
      },
      onCheck(checkedKeys) {
        this.checkedKeys = checkedKeys
      },

      /** 获取已选择的角色数据 */
      loadSelectedRoleAppTree(tenantId, roleId) {
        let that = this
        simpleTenantRoleAppTree(tenantId, roleId).then(res => {
          if (res.success) {
            that.selectedRoleApp = [...res.result];
            that.checkedKeys = [];
            that.selectedRoleApp.forEach(function (selectedApp) {
              queryRolePermission(roleId, selectedApp.appId, {}).then((res) => {
                if (res.result && res.result.length > 0) {
                  let permissionIds = res.result
                  queryRoleLeafPermission(roleId, selectedApp.appId, {}).then((res) => {
                    that.setAppPermission(selectedApp, permissionIds, res.result)
                  })
                }
              })
            })
          } else {
            this.$message.error(res.message)
          }
        }).finally(() => {})
      },

      onCheckRoleApp(checkedKeys) {
        this.checkedKeysRoleApp = checkedKeys
      },
      onSelectApp(selectedKeys) {
        let that = this;
        this.selectedAppKeys = selectedKeys;
        this.selectedKeysRole = selectedKeys;
        let selectedApp
        if (selectedKeys.length > 0) {
          let curKey = selectedKeys[0];
          that.selectedRoleApp.forEach(function (item) {
          if (curKey === item.key) {
              selectedApp = item;
              return true;
            }
          })
          if (selectedApp) {
            that.selectedApp = selectedApp;
            this.loadPermissionData(this.tenantId, that.selectedApp);
           }
        } else {
          this.permissionData = []
          this.checkedPermission = [];
        }
      },

      /** 从可选角色列表中选择角色 */
      selectTenantRole() {
        let that = this;

        if (that.checkedKeys.length === 0) {
          that.$message.warning('请选择角色列表');
          return false;
        }

        let selectedRoleId = [];
        // 从可选角色列表中选择
        this.tenantRoleTree.forEach(function (item) {
          // 角色是否checked
          let isSelected = that.checkedKeys.findIndex(key => key === item.roleId) !== -1;
          // 已选中
          if (isSelected && item['roleId']) {
              selectedRoleId.push(item['roleId'])
          }
        });

        let selectRoleApp = [];
        that.tenantRoleTree.forEach(function (item) {
           let tToleId = item.roleId;
           let tAppList = item.apps;
          if (tToleId) {
            let isSelected = selectedRoleId.findIndex(key => key === item.roleId) !== -1;
            if (isSelected && tAppList) {
              // 获取角色下对应的应用列表
              let tList = selectRoleApp.concat(tAppList);
              if (tList && tList.length > 0) {
                 tList.forEach(function(item) {
                })
                selectRoleApp = [...tList];
              }
            }
          }
        });

        selectRoleApp.forEach(function (item) {
          let isContain = false
          that.selectedRoleApp.forEach(function (subItem) {
            if (subItem.appId === item.appId) {
              isContain = true;
            }
          })
          if (!isContain) {
            that.selectedRoleApp.push(item)
          }
        })
      },
      /** 取消已选择的角色 */
      cancelTenantRole() {
        let that = this;

        if (that.checkedKeysRoleApp.length === 0) {
          that.$message.warning('请选择应用列表');
          return false;
        }

        let leftRoleTree = [];
        this.selectedRoleApp.forEach(function (item, index) {
          let isSelected = that.checkedKeysRoleApp.findIndex(key => key === item.key) !== -1;
          if (!isSelected) {
            leftRoleTree.push(item);
          }
        });
        that.checkedKeysRoleApp = [];
        that.selectedRoleApp = leftRoleTree;
        let selectedCancel = true
        leftRoleTree.forEach(function (item) {
          if (item.key.indexOf(that.selectedKeysRole) !== -1) {
            selectedCancel = false
          }
        })
        if (selectedCancel) {
          that.selectedKeysRole = []
          that.permissionData = []
        }
      },

      /** 获取应用权限信息 */
      loadPermissionData(tenantId, selectedApp) {
        let params = {};
        let that = this;
        queryTenantRoleAppTree(tenantId, selectedApp.roleId, selectedApp.appId, params).then((res) => {
          that.permissionData = res.result.treeList
          that.allTreeKeys = res.result.ids
          let key = that.getKey(selectedApp.roleId, selectedApp.appId);
          if (that.appPermissionMap.has(key)) {
            let leafPermissionId = that.appPermissionMap.get(key).leafPermissionIds
            that.checkedPermission = leafPermissionId;
            that.defaultCheckedKeys = leafPermissionId;
            that.expandedKeysss = that.allTreeKeys;
          }
        })
      },

      onCheckPermission (o, e) {
        this.checkedPermission = o
        let halfChecked = e.halfCheckedKeys
        this.setAppPermission(this.selectedApp, halfChecked.concat(this.checkedPermission), this.checkedPermission)
      },

      /** 保存数据集合处理 */
      setAppPermission (selectedApp, pPermissionIds, leafPermissionIds) {
        let obj = {
          roleId: selectedApp.roleId,
          appId: selectedApp.appId,
          permissionIds: pPermissionIds,
          leafPermissionIds: leafPermissionIds
        }
        let key = this.getKey(selectedApp.roleId, selectedApp.appId);
        if (this.appPermissionMap.has(key)) {
          this.appPermissionMap.get(key).permissionIds = [...pPermissionIds];
          this.appPermissionMap.get(key).leafPermissionIds = [...leafPermissionIds];
        } else {
          this.appPermissionMap.set(key, obj);
        }
      },

      setAppChecked (roleId, checkedAppKeys) {
        if (checkedAppKeys && checkedAppKeys.length > 0) {
          checkedAppKeys.forEach(element => {
            if (!this.appPermissionMap.has(element)) {
                this.setAppPermission(roleId, [], []);
            }
          });
        }
      },
      getPermissionIds (key) {
        if (this.appPermissionMap.has(key)) {
          return this.appPermissionMap.get(key).permissionIds;
        }
        return [];
      },

      getKey(roleId, appId) {
         return String(roleId) + String(appId);
      }

    }
  }
</script>
